﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Hosting;

namespace SX.Utils
{
    public static class HandlebarHelpers
    {
        /// <summary>
        /// 日期格式化
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="context"></param>
        /// <param name="arguments"></param>
        public static void Date(TextWriter writer, dynamic context, params object[] arguments)
        {
            DateTime dt;
            Dictionary<string, object> paras = new Dictionary<string, object>();
            string defaultFmt;
            if (arguments[0] is Dictionary<string, object>)
            {
                dt = DateTime.Now;
                paras = arguments[0] as Dictionary<string, object>;
            }
            else
            {
                dt = CommonHelper.ToDateTime(arguments[0]);
                if (arguments.Length == 2)
                {
                    paras = arguments[1] as Dictionary<string, object>;
                }
            }
            if (paras.ContainsKey("fmt"))
            {
                defaultFmt = paras["fmt"].ToString();
            }
            else if (paras.ContainsKey("format"))
            {
                defaultFmt = paras["format"].ToString();
            }
            else if (paras.ContainsKey("f"))
            {
                defaultFmt = paras["f"].ToString();
            }
            else
            {
                defaultFmt = "yyyy-MM-dd";
            }
            writer.Write(dt.ToString(defaultFmt));
        }

        public static void Asset(TextWriter writer, dynamic context, params object[] arguments)
        {
            string url = arguments[0].ToString();
            string assetVersion = ConfigHelper.GetApp("assetVersion", "1.0");
            url = UrlHelper.GetUrl(url) + (url.IndexOf("?") > 0 ? "&" : "?") + "v=" + assetVersion;
            writer.Write(url);
        }

        /// <summary>
        /// url 路径
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="context"></param>
        /// <param name="arguments"></param>
        public static void Url(TextWriter writer, dynamic context, params object[] arguments)
        {
            string url = arguments[0].ToString(); 
            writer.Write(UrlHelper.GetUrl(url));
        }
    }
}
